package com.qidian.buy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @date 2023/5/22 10:40
 */
public class JSONTools {
    private static ObjectMapper objectMapper = new ObjectMapper();


    public static <T> List<T> json2list(String json,Class<T> clazz){
        try {
            return objectMapper.readValue(json,new TypeReference<List<T>>(){});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    };

    public static <T> T json2object(String json,Class<T> clazz){
        try {
            return objectMapper.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    };

    public static String object2json(Object obj){
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
